// mobile bind
// ============

define(['zepto', 'utils', 'wxpay', 'countDown'], function($, utils, wxpay){
  return {
    init: function(data) {
      utils.configWeixin(data.jsConfig, true, 
      {
        name : "陆老师小课堂，视频讲解课程。开始报名啦~",
        desc : "陆老师亲自录制，一至三年级小学奥数知识点精讲课程在线视频，附赠课后习题与答疑",
        link : window.__CTX__.root + "/vedio-course",
        cover : window.__CTX__.resource + "/images/video-course/video-course-banner.png"
      });
      this.preparePay();
      this.bindMobileBindingPageEvent();
    },
    
    preparePay: function() {
      var that = this;
      $(document).on("click", "button[type='submit']", function(e){
        
        $.showPreloader('正在提交支付数据')
        
        var $form = $(document).find("form");
        var parameters = $form.serializeArray()
        
        parameters.push({name: "currentUrl", value: location.href.split('#')[0]});
        parameters.push({name: "token", value: that.token});
        
        $.ajax({
          type: $form.attr('method'),
          url:  $form.attr('action'),
          data: parameters
        }).done(function(response) {
          $.hidePreloader()
          utils.processResult(response, that.configWxPay.bind(that), function(result) {
            $.toast(result.message || '请求支付数据失败')
            if(result.code != 0) {
              setTimeout(function() {
                location.href = window.__CTX__.root + '/vedio-course/pay';
              }, 2000)
            }
          })
        })
      })
    },
    
    /**
     * Bind mobile binding page event
     */
    bindMobileBindingPageEvent: function() {
      var that = this,
        $mobile = $('input[name="mobile"]'),
        $code = $('input[name="code"]');

      // On requesting verify code
      $(document).on('click', '#get-code', function(e) {
        e.preventDefault()
        
        var $button = $(e.currentTarget), mobile = $mobile.val().trim()
        if (that.isMobile(mobile)) {
          // Disable button
          $button.css('pointer-events', 'none')
          // Request verifiy code
          that.requestVerifyCode(mobile, function(data) {
            
            that.token = data.token;
            
            $button.countdown('s后重试', 60, function() {
              $button.css('pointer-events', 'initial').text('获取验证码')
            })
          }, function() {
            $button.css('pointer-events', 'initial')
          })
        } else {
          $.toast('请输入正确的手机号码')
        }
      })
    },
    
    /**
     * Check mobile value is valid or not
     */
    isMobile: function(mobile) {
      return mobile && /^((13)|(15)|(17)|(18))\d{9}$/.test(mobile)
    },
    
    /**
     * Request server to send verifiy code to mobile
     */
    requestVerifyCode: function(mobile, success, failure) {
      $.showIndicator()
      utils.requestVerifyCode(mobile, function(result) {
        $.hideIndicator()
        $.toast('验证码发送成功')
        success && success(result.data)
      }, failure)
    },
    
    /**
     * Handle success WeChat pay, config WeChat JS SDK and invoke pay
     */
    configWxPay: function(result) {
      console.log(result);
      var that = this
          jsConfig = result.data.jsConfig,
          payConfig = result.data.payConfig

      wxpay.injectConfig(jsConfig, ['chooseWXPay'])
      wxpay.invokePay(payConfig, function(res) {
        $.toast('支付成功，正在为您跳转')
        setTimeout(function() {
            location.href = window.__CTX__.root + '/vedio-course/result';
        }, 1000)
      })
    }
  }
})